package com.sip.stream.utils.zfy.muxer;

import com.sip.stream.utils.zfy.GSMediaSampleData;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

public class GSBareStreamWriter {
    private static final String TAG = "GSBareStreamWriter";

    private String filePath;
    private boolean isRecording = false;
    private int preCount = 0;
    private FileOutputStream tempStream;

    public GSBareStreamWriter(String str) {
        this.filePath = str;
        setUpMediaMuxer();
    }

    private boolean setUpMediaMuxer() {
        try {
            this.tempStream = new FileOutputStream(this.filePath + ".braStream");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return true;
        }
    }

    public void start() {
        this.isRecording = true;
    }

    public void stop() {
        this.isRecording = false;
    }

    private void closeStream() {
        try {
            FileOutputStream fileOutputStream = this.tempStream;
            if (fileOutputStream != null) {
                fileOutputStream.close();
                this.tempStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public synchronized boolean writeSampleData(GSMediaSampleData gSMediaSampleData) {
        if (!this.isRecording) {
            closeStream();
            return false;
        }
        ByteBuffer byteBuf = gSMediaSampleData.getByteBuf();
        byteBuf.slice();
        int remaining = byteBuf.remaining();
        byte[] bArr = new byte[remaining];
        byteBuf.get(bArr);
        try {
            writeBareStreamHeader(this.tempStream, !gSMediaSampleData.isAudio() ? 1 : 0, gSMediaSampleData.getBufferInfo().flags, gSMediaSampleData.getPresentationTimeUs(), remaining);
            this.tempStream.write(bArr);
            this.tempStream.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            closeStream();
            return false;
        }
    }

    private boolean writeBareStreamHeader(FileOutputStream fileOutputStream, int i, int i2, long j, int i3) throws IOException {
        fileOutputStream.write(BarSteamTool.int2Bytes(i));
        fileOutputStream.write(BarSteamTool.int2Bytes(i2));
        fileOutputStream.write(BarSteamTool.long2Bytes(j));
        fileOutputStream.write(BarSteamTool.int2Bytes(i3));
        return true;
    }
}
